package menulogic

import (
	"context"
	"time"
	"zhongxc.cc/admin-user/internal/domain"
	"zhongxc.cc/admin-user/internal/model"
	"zhongxc.cc/admin-user/internal/svc"
	"zhongxc.cc/grpc-common/admin-user/types/menu"

	// "zhongxc.cc/admin-user/api/proto/menu/internal/svc"
	// "zhongxc.cc/admin-user/api/proto/types/menu"

	"github.com/zeromicro/go-zero/core/logx"
)

type ListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
	menuDomain *domain.MenuDomain
}

func NewListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListLogic {
	return &ListLogic{
		ctx:        ctx,
		svcCtx:     svcCtx,
		Logger:     logx.WithContext(ctx),
		menuDomain: domain.NewMenuDomain(svcCtx.Db),
	}
}

func (l *ListLogic) List(in *menu.PageInfo) (*menu.MenuListPageResponse, error) {
	// todo: add your logic here and delete this line
	ctx, cancelFunc := context.WithTimeout(context.Background(), time.Second*5000)
	defer cancelFunc()

	userInfo := l.ctx.Value("userinfo")
	logx.Info(userInfo)

	pageResult, err := l.menuDomain.List(ctx, int(in.Page), int(in.Limit), in.Keyword)
	if err != nil {
		return nil, model.ErrorQueryFail
	}
	menuList := pageResult.Items.([]*model.SysMenu)
	var menuItemList []*menu.MenuItemInfo
	for _, item := range menuList {
		menuItem := &menu.MenuItemInfo{
			MenuId:      item.MenuId,
			Name:        item.Name,
			ParentId:    item.ParentId,
			Url:         item.Url,
			Perms:       item.Perms,
			Type:        item.Type,
			Icon:        item.Icon,
			OrderNum:    item.OrderNum,
			CreatedBy:   item.CreatedBy,
			CreatedTime: item.CreatedTime.Format("2006-01-02 15:04:05"),
			UpdatedBy:   item.UpdatedBy,
			UpdatedTime: item.UpdatedTime.Format("2006-01-02 15:04:05"),
		}
		menuItemList = append(menuItemList, menuItem)
	}
	return &menu.MenuListPageResponse{
		Page:      int64(pageResult.Page),
		Rows:      int64(pageResult.Rows),
		PageCount: int64(pageResult.PageCount),
		Total:     pageResult.Total,
		Items:     menuItemList,
	}, nil
}
